package com.hnevc.myspeaker.Kuaidi;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.hnevc.myspeaker.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KuaiDiActivity extends AppCompatActivity {
    private static final String TAG = "KuaiDiActivity";
    KdniaoTrackQueryAPI api;
    private Toolbar toolbar;
    /**
     * 快递编号
     */
    private TextView mText1;
    /**
     * 请输入快递编号
     */
    private EditText mEdit1;
    /**
     * 查询
     */
    private Button mBtnSearch;
    private MyListView mListKuaidi;
    private MyAdapter adapter;
    private List<Map> list;
    /**
     * 公司编号
     */
    private TextView mText2;
    /**
     * 请输入公司编号
     */
    private EditText mEdit2;
    private TextView mTextLanjianshijian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuai_di);
        initView();

        setToolBar();
        api = new KdniaoTrackQueryAPI();

    }


    private void initView() {
        toolbar = findViewById(R.id.action_bar);
        mText1 = findViewById(R.id.text1);
        mEdit1 = findViewById(R.id.edit1);
        mBtnSearch = findViewById(R.id.btn_search);
        mListKuaidi = findViewById(R.id.list_kuaidi);
        mText2 =  findViewById(R.id.text2);
        mEdit2 = findViewById(R.id.edit2);
        mTextLanjianshijian =  findViewById(R.id.text_lanjianshijian);

        list = new ArrayList<>();
        adapter = new MyAdapter(list, KuaiDiActivity.this);
        mListKuaidi.setAdapter(adapter);
        mBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String code = mEdit2.getText().toString();
                String no = mEdit1.getText().toString();
                initData(code,no);
            }
        });

    }

    private void initData(final String code, final String no) {
        list.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, "run: "+code+no);
                    String dbl = api.getOrderTracesByJson(code, no);
                    JSONObject jsonObject = new JSONObject(dbl);
                    JSONArray jsonArray = jsonObject.optJSONArray("Traces");
                    Log.d(TAG, "run: " + dbl);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        Map<String, String> map = new HashMap<>();
                        String info = jsonArray.getJSONObject(i).optString("AcceptStation");
                        Log.d(TAG, "run: " + info);
                        map.put("info", info);
                        String acceptTime = jsonArray.getJSONObject(i).optString("AcceptTime");
                        String[] s = acceptTime.split(" ");
                        map.put("date", s[0]);
                        map.put("time", s[1]);
                        list.add(map);
                    }

                   runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           if(list.size() > 1){
                               mTextLanjianshijian.setText("揽件时间："+list.get(0).get("date")+" "+list.get(0).get("time"));
                           }
                           Collections.reverse(list);
                           adapter.notifyDataSetInvalidated();
                       }
                   });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void setToolBar() {
        setSupportActionBar(toolbar);
        View view = LayoutInflater.from(this).inflate(R.layout.toolbar_layout, null);
        ActionBar actionBar = getSupportActionBar();
        ActionBar.LayoutParams params = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
        );
        actionBar.setCustomView(view, params);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        TextView textView = view.findViewById(R.id.textView_main);
        textView.setText("快递查询");
        ImageView imageView = view.findViewById(R.id.menu_main);
        imageView.setImageResource(R.mipmap.back);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    class MyAdapter extends BaseAdapter {
        private List<Map> list;
        private Context context;

        public MyAdapter(List<Map> list, Context context) {
            this.list = list;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            View v = null;
            if (v == null) {
                v = LayoutInflater.from(context).inflate(R.layout.layout_item, viewGroup, false);
                viewHolder = new ViewHolder(v);
                v.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) v.getTag();
            }
            Map<String, String> map = list.get(i);
            viewHolder.mTextDate.setText(map.get("date"));
            viewHolder.mTextTime.setText(map.get("time"));
            viewHolder.mTextInfo.setText(map.get("info"));
            return v;
        }

        class ViewHolder {
            View view;
            TextView mTextDate;
            TextView mTextTime;
            TextView mTextInfo;

            ViewHolder(View view) {
                this.view = view;
                this.mTextDate = view.findViewById(R.id.text_date);
                this.mTextTime = view.findViewById(R.id.text_time);
                this.mTextInfo = view.findViewById(R.id.text_info);
            }
        }
    }
}
